package com.java.controller;

import com.java.bean.Admin;
import com.java.bean.Message;
import com.java.mvc.Body;
import com.java.service.AdminService;
import com.java.service.CourierService;
import com.java.service.ExpressService;
import com.java.service.UserService;
import com.java.util.JSONUtil;
import com.java.util.UserUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@SuppressWarnings("all")
public class AdminController {

    @Body("/admin/logout.do")
    public String logout(HttpServletRequest req, HttpServletResponse resp) {
        req.getSession().invalidate();
        return JSONUtil.toJSON(new Message(0, "退出成功"));
    }

    @Body("/admin/login.do")
    public String login(HttpServletRequest req, HttpServletResponse resp) {
        final String name = req.getParameter("name");
        final String password = req.getParameter("password");
        final Admin admin = new Admin(name, password, req.getRemoteAddr(), new Timestamp(new Date().getTime()));
        final Admin a = AdminService.login(admin);
        final Message message;
        if (a != null) {
            req.getSession().invalidate();
            req.getSession().setAttribute("admin", a);
            message = new Message(0, "登录成功！");
        } else {
            message = new Message(-1, "登录失败，用户名或密码错误！");
        }
        return JSONUtil.toJSON(message);
    }

    @Body("/admin/loginInfo.do")
    public String loginInfo(HttpServletRequest req, HttpServletResponse resp) {
        final Admin user = UserUtil.getAdmin(req.getSession());
        if (user != null)
            return JSONUtil.toJSON(new Message(0, user));
        else
            return JSONUtil.toJSON(new Message(-1));
    }


    @Body("/admin/views/console.do")
    public String console(HttpServletRequest req, HttpServletResponse resp) {
        final List<Map<String, Integer>> data = new ArrayList<>(ExpressService.console());
        data.add(UserService.console());
        data.add(CourierService.console());
        final Message message;
        if (data != null) {
            message = new Message(0, data);
        }else {
            message = new Message(-1, "数据获取失败", null);
        }
        return JSONUtil.toJSON(message);
    }

}
